#!/bin/bash

# 设置脚本中出现的任何错误立即退出
set -e

# 项目根目录
PROJECT_DIR=$(cd "$(dirname "$0")"; pwd)

# 进入项目目录
cd "$PROJECT_DIR"

# 清理以前的构建
echo "Cleaning previous builds..."
sudo source /etc/profile
mvn clean

# 编译项目
echo "Building the project..."
mvn compile

# 运行单元测试
echo "Running tests..."
mvn test

# 打包项目，生成可执行的JAR
echo "Packaging the project..."
mvn package

# 查找生成的JAR文件
JAR_FILE=$(find target -name "*.jar" | grep -v "original" | head -n 1)

if [ -z "$JAR_FILE" ]; then
    echo "Error: JAR file not found!"
    exit 1
fi

echo "Build successful! JAR file located at: $JAR_FILE"

# 可选：移动JAR到指定目录
# mv "$JAR_FILE" /path/to/deploy/directory

# 可选：清理target目录
# mvn clean

echo "Packaging script completed successfully."